const path = require("path");
const { Controller } = require("egg");
const { PassThrough } = require("stream");

class HomeController extends Controller {
  async index() {
    const { ctx } = this;
    ctx.state.user = "张三";
    await ctx.render("index.html");
  }

  appCfg() {
    const { ctx, app } = this;
    if (ctx.query?.id) {
      ctx.body = app.config[ctx.query.id];
    } else {
      ctx.body = app.config;
    }
  }

  async redis() {
    console.log("连接上了");
    const {
      ctx,
      app: { redis },
    } = this;
    ctx.set({ "Content-Type": "text/event-stream" });
    let i = 0;
    let stream = new PassThrough();

    const writeSome = (msg) => {
      stream.write(`id: ${+new Date()}\n`); // 消息数据
      stream.write(`data: ${msg}\n`); // 消息数据
      stream.write("retry: 1000\n"); // 重连时间
      stream.write("\n\n"); // 消息结束
    };

    //模拟持续服务端传值给客户端
    writeSome();

    const subChannel = "test";
    redis.subscribe(subChannel, (_channel, message) => {
      const msg = subChannel + "：" + (message===1?"订阅成功":"订阅失败") + " " + new Date().toLocaleString();
      writeSome(msg);
    });
    redis.on("message", (_channel, message) => {
      const msg = _channel + "：" + message + " " + new Date().toLocaleString();
      writeSome(msg);
    });

    ctx.body = stream;
    //流关闭，客户端主动断开连接
    stream.on("close", () => {
      console.log("连接断开");
    });
  }
}

module.exports = HomeController;
